package com.hns.can.common.aop.exception;

import org.aspectj.lang.annotation.AfterThrowing;
import org.aspectj.lang.annotation.Aspect;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;

import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.Date;

/**
 * 异常通知
 * @author:zhangy
 * @email:zhangyu2222z@sina.cn
 * @version Revision 2.0.0
 */
@Aspect
@Component
public class AdviceExceptionHandler {
	private static final Logger logger = LoggerFactory.getLogger(AdviceExceptionHandler.class);
//	private static boolean notice = false;
	private static String exceptionId = "";
	/**
	 * 自定义异常通知，无论报什么异常，均以自定义business异常抛出
	 * @param exception
	 * @author:zhangyu
	 * @email:zhangyu2222z@sina.cn
	 */
//	@AfterThrowing(value="execution(* com.hns.can..*.*Service.*(..))",argNames="exception",throwing="exception")
//	@AfterThrowing(value="execution(* com.hns.can..*.*Controller.*(..))",argNames="exception",throwing="exception")
	@AfterThrowing(value="execution(* com.hns.can..*.*(..))",argNames="exception",throwing="exception")
	public void afterThrowingAdvice(Exception exception){
		StackTraceElement[] st = exception.getStackTrace();
		for (StackTraceElement stackTraceElement : st) {
			String exclass = stackTraceElement.getClassName();
			String method = stackTraceElement.getMethodName();
			if (exclass.contains("com.hns.can") && !exclass.equals("com.hns.frame.service.CommonService")
					//&& exclass.contains(".service.")
					&& !exclass.contains("$")) {
				//生成异常ID
				DateFormat fmt = new SimpleDateFormat("yyyyMMddHHmmssss");
				String exId = fmt.format(new Date());

				if(!exId.equals(exceptionId)){
					//目前只局限在com.hns.can下service或者controller中，只显示异常原因
					logger.error("\n====异常ID为" + exId + " : [类:" + exclass + "]调用[" + method + "]时在第[" + stackTraceElement.getLineNumber()
							+ "]行代码处发生异常!\n异常原因:" + exception.getCause() + "\r\n");
					exceptionId = exId;
				}
				break;
			}
		}
	}

//	@Around("execution(* com.hns.can..*.*Controller.*(..))")
//	public void around(ProceedingJoinPoint pjp) throws Throwable{
//		try{
//			pjp.proceed();
//		}catch (Exception ex){
//			System.out.println("模拟抛出异常后的增强处理...");
//		}
//	}

//	@AfterThrowing(throwing="ex",pointcut="execution(* com.hns.can..*.*(..))")
//	public void doRecoveryActions(Throwable ex){
//		System.out.println("目标方法中抛出的异常:"+ex);
//		if(!notice){
//			System.out.println("模拟抛出异常后的增强处理...");
//		}
//		notice = !notice;
//		System.out.println("模拟抛出异常后的增强处理..."+notice);
//	}
	
}
